package com.ruyuan.seckill.service.cartbuilder.impl;


import com.ruyuan.seckill.cache.Cache;
import com.ruyuan.seckill.domain.enums.CachePrefix;
import com.ruyuan.seckill.domain.vo.CartSkuVO;
import com.ruyuan.seckill.domain.vo.PromotionScriptVO;
import com.ruyuan.seckill.service.cartbuilder.ScriptProcess;
import com.ruyuan.seckill.utils.DateUtil;
import com.ruyuan.seckill.utils.JsonUtil;
import com.ruyuan.seckill.utils.ScriptUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ScriptProcessImpl implements ScriptProcess {
    @Autowired
    private Cache cache;

    /**
     * 计算促销优惠价格
     *
     * @param script 脚本
     * @param params 参数
     * @return 优惠后的价格
     */
    @Override
    public Double countPrice(String script, Map<String, Object> params) {
        try {
            //计算促销优惠  返回优惠后的金额
            Object price = ScriptUtil.executeScript("countPrice", params, script);
            //设置返回值
            Double result = Double.parseDouble(price.toString());
            log.debug("入参" + JsonUtil.objectToJson(params));
            log.debug("script 脚本：" + script);
            log.debug("根据促销脚本计算价格：");
            log.debug(result.toString());
            return result;
        } catch (Exception e) {
            log.error("根据促销脚本计算价格异常:");
            log.error(e.getMessage());
        }
        return 0D;
    }

    /**
     * 获取购物车级别促销脚本信息
     *
     * @param sellerId
     * @return
     */
    @Override
    public List<PromotionScriptVO> readCartScript(Integer sellerId) {
        return (List<PromotionScriptVO>) cache.get(CachePrefix.CART_PROMOTION.getPrefix() + sellerId);
    }

    @Override
    public Double getShipPrice(String script, Map<String, Object> params) {
        try {
            //计算运费  返回运费金额
            Object price = ScriptUtil.executeScript("getShipPrice", params, script);
            //设置返回值
            Double result = Double.parseDouble(price.toString());
            log.debug("入参" + JsonUtil.objectToJson(params));
            log.debug("script 脚本：" + script);
            log.debug("根据脚本计算运费：");
            log.debug(result.toString());
            return result;
        } catch (Exception e) {
            log.error("根据脚本计算运费异常:");
            log.error(e.getMessage());
        }
        return 0D;
    }

    /**
     * 获取sku促销活动信息
     *
     * @param skuId 货品id
     * @return
     */
    @Override
    public List<PromotionScriptVO> readSkuScript(Integer skuId) {
        return (List<PromotionScriptVO>) cache.get(CachePrefix.SKU_PROMOTION.getPrefix() + skuId);
    }

    /**
     * 获取sku级别促销脚本信息
     *
     * @param skuList
     * @return
     */
    @Override
    public List<PromotionScriptVO> readSkuScript(List<CartSkuVO> skuList) {
        List<String> skuKeys = new ArrayList<>();
        for (CartSkuVO cartSkuVO : skuList) {
            skuKeys.add(CachePrefix.SKU_PROMOTION.getPrefix() + cartSkuVO.getSkuId());
        }
        List<List<PromotionScriptVO>> skuScripts = cache.multiGet(skuKeys);
        List<PromotionScriptVO> result = new ArrayList<>();
        for (List<PromotionScriptVO> scriptVO : skuScripts) {
            if (scriptVO != null && !scriptVO.isEmpty()) {
                result.addAll(scriptVO);
            }
        }
        return result;
    }

    /**
     * 获取活动是否有效
     *
     * @param script
     * @return true：活动有效，false:活动无效
     */
    @Override
    public Boolean validTime(String script) {
        try {
            Map params = new HashMap();
            params.put("$currentTime", DateUtil.getDateline());
            Boolean result = (Boolean) ScriptUtil.executeScript("validTime", params, script);
            log.debug("script 脚本:{}" + script);
            log.debug("根据促销脚本判断活动是否有效：{}", result);
            return result;
        } catch (Exception e) {
            log.error("根据促销脚本计算价格异常:", e);
        }
        return false;
    }

    /**
     * 读取优惠券脚本
     *
     * @param couponId 优惠券id
     * @return
     */
    @Override
    public String readCouponScript(Integer couponId) {
        //优惠券级别缓存key
        String cacheKey = CachePrefix.COUPON_PROMOTION.getPrefix() + couponId;
        return (String) this.cache.get(cacheKey);
    }
}
